<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
var _title;	// 业务标题
var _issueId; // 业务主键

var _doSurplusWork = _documentContext + "/supervise/doSuperviseReportWork";// （流程启动成功后业务数据的相关操作）业务模块自己定义的业务处理方法，以供框架在提交完成后，进行触发

var rootTable;
$(function(){
	
	if("<c:out value='${reportITF}' />"=="0"){
		$.messager.alert("提示",'内网推送接口配置错误，您的信息将无法推送至内网');
	}else if("<c:out value='${attachDL}' />"=="0"){
		$.messager.alert("提示",'附件下载接口配置错误，您发布的附件将无法查看');
	}
	
	_issueId=$("#docId").val();
	
	$("#docName").textbox({
		 required : true,   
		 editable:"<c:out value='${noFlow}'/>"=="1"
	});
	
	//附件start
	var controlId="fileUpload";//自定义控件名前缀
	var delFlag=("<c:out value='${noFlow}' />"=="1" || _issueType=="todo" && actionPermissionJson.ModifyAttach=="true")?"1":"0";//显示删除按钮：0，不显示；1，显示
	var addFlag=("<c:out value='${noFlow}' />"=="1" || _issueType=="todo" && actionPermissionJson.ModifyAttach=="true")?"1":"0";//添加按钮可用：0，不可用；1，可用
	var showControlFlag=("<c:out value='${noFlow}' />"=="1" ||_issueType=="todo" && actionPermissionJson.ModifyAttach=="true")?"1":"0";//显示file控件和上传按钮：0，不显示；1，显示
	//var docType="";//流程状态：为done时候控制file控件和上传按钮不显示----issue.js已有
	var attachNo="0";//查询已有附件条件
	var attachVersion="0";//查询已有附件条件
	var attachType="AS";//查询已有附件条件
	
	if("<c:out value='${noFlow}' />"=="1"){
		$("#fileDiv").panel({
		    href:_synergyContext+'/basic/synAttach/gotoSynAttachPage?docId='
		    	+_issueId+'&controlId='+controlId+'&delFlag='+delFlag+'&addFlag='+addFlag
		    	+'&showControlFlag='+showControlFlag+'&docType=todo'
		    	+"&attachNo="+attachNo+"&attachVersion="+attachVersion
				   +"&attachType="+attachType+"&fileReadOnly="+fileReadOnly,
		    border:false,//不显示边框
		    cache:false//不从缓存加载面板
		});
	}else{
		//设置附件在word控件中打开后是否只读，默认只读true，如果为false，文件可编辑保存
		var fileReadOnly= _issueType!="todo" || actionPermissionJson.ModifyAttach!="true";
		$("#fileDiv").panel({
		    href:_synergyContext+'/basic/synAttach/gotoSynAttachPage?docId='
		    	+_issueId+'&controlId='+controlId+'&delFlag='+delFlag+'&addFlag='+addFlag
		    	+'&showControlFlag='+showControlFlag+'&docType='+_issueType
		    	+"&attachNo="+attachNo+"&attachVersion="+attachVersion
				   +"&attachType="+attachType+"&fileReadOnly="+fileReadOnly,
		    border:false,//不显示边框
		    cache:false//不从缓存加载面板
		});
	}
	
	//附件end
	
	//表格加载
	rootTable=$('#superviseReportTable').datagrid({
	    url:'<c:url value="/supervise/superviseListDateFirstPart" />',
	    queryParams:getParams(''),//提交参数
	    showHeader:false,
	    //toolbar:'#superviseReportToolbar',//表头工具栏
	    pagination:true,//显示分页  
	    pagePosition:'bottom',//分页栏出现位置
	    pageNumber:1,//初始页码
	    pageSize:10,//初始每页显示记录数量
	    nowrap: false,//设置内容多时换行，false换行
	    singleSelect:true,
	    columns:[[
			{field:'docId',title:'',width:"100%",formatter: function(value,row,index){
				if($("input[name='superviseIds'][value='"+value+"']").size()==0){
					$("#superviseReportForm").append('<input type="hidden" name="superviseIds" value="'+value+'">');
				}
				return (isNotBlank(row.displayNumber)?("<font color='blue'>（"+row.displayNumber+"）</font>"):"")+
				(isNotBlank(row.endTime)?"<font color='red'>（"+dataFormatStr(new Date(row.endTime),"yyyy-MM-dd")+"）</font>":"")+row.docName+
				(isNotBlank(row.bak3)?("<font color='grey'>（"+row.bak3+"）</font>"):"");
			}}
			
	    ]],
	    rowStyler:function(index,row){
	    	return "font-weight:bold";
	    },
	    onClickCell: function (rowIndex, field, value) {
	    	IsCheckFlag = false;
		},
		onSelect: function (rowIndex, rowData) {
			if (!IsCheckFlag) {
				IsCheckFlag = true;
				rootTable.datagrid("unselectRow", rowIndex);
			}
			rootTable.datagrid("expandRow",rowIndex);
			//rootTable.datagrid('collapseRow', rowIndex);
		},
		onLoadSuccess:function(data){
			if(data.total>0){
				rootTable.datagrid("expandRow",0);
				setTimeout(function(){
					rootTable.datagrid("resize");
				},1000);
			}
		},
	    view: detailview,
	    detailFormatter:function(index,row){
			return '<div><table id="ddv-' + index + '"></table></div>';
		},
		onExpandRow: function(parentIndex,parentRow){
			$('#ddv-'+parentIndex).datagrid({
				url:"<c:url value='/supervise/superviseListDateSecondPart'/>",
				queryParams:getParams(parentRow.docId),//提交参数
				fitColumns:true,
				singleSelect:true,
				rownumbers:true,
				//loadMsg:'',
				height:'auto',
				columns:[[
					{field:'docName',title:'事项名称',width:"35%",align:'left',halign:'center'},
					{field:'draftOrg',title:'承办部门',width:"15%",align:'center',halign:'center'},
					{field:'bak3',title:'限办时间',width:"10%",align:'center',halign:'center',formatter: function(value,row,index){
						return value==""||value==null?"":value.substring(0,10);
					}},
					{field:'docState',title:'当前状态',width:"15%",align:'center',halign:'center',formatter: function(value,row,index){
						if(value==null || value=="" || value=="DR"){
							return "未提交反馈";
						}else if(value=="TR"){
							return "反馈审批中";
						}else if(value=="BR"){
							return "已提交反馈";
						}else if(value=="TM"){
							return "已废止";
						}else if(value=="DE"){ 
							return "已收回";
						}
					}},
					{field:'bak1',title:'操作',width:"15%",align:'center',halign:'center',formatter: function(value,row,index){
						value=row.docState;
						if(value=="TR" || value=="BR"){
							return "<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"');\">查看</a>";
						}
					}}
				]],
				onResize:function(){
					rootTable.datagrid('fixDetailRowHeight',parentIndex).datagrid("resize");
				},
				onLoadSuccess:function(){
					setTimeout(function(){
						rootTable.datagrid('fixDetailRowHeight',parentIndex).datagrid("resize");
					},1000);
				}
			});
		}
	});
	
	//查询按钮绑定点击事件
	$("#searchButton").click(function(){ 
		rootTable.datagrid({ queryParams:getParams('')});
	});

	
	$("#editBranchDiv").dialog({
		title:"督办事项详情",//标题
		width: 950,//宽度
	    height: 450,//高度
	    closed: true,//初始关闭
	    modal: true,
	    cache: false//缓存
	});
});

function getParams(parentId){
	var jsonObj=new Object();
	if($('input[name="orgCode"]').size()==1 && $('input[name="orgCode"]').val()!=""){
		jsonObj.orgCode=$('input[name="orgCode"]').val();
	}
	if($('input[name="state"]').val()!=""){
		jsonObj.state=$('input[name="state"]').val();
	}
	if($('input[name="startDate"]').val()!=""){
		jsonObj.startDate=$('input[name="startDate"]').val()+" 00:00:00";
	}
	if($('input[name="endDate"]').val()!=""){
		jsonObj.endDate=$('input[name="endDate"]').val()+" 23:59:59";
	}
	if(isNotBlank(parentId)){
		jsonObj.parentId=parentId;
	}
	jsonObj.node="root";
	jsonObj.reportFlag="1";
	/*jsonObj.operationState="1";
	jsonObj.reportId="<c:out value='${docSuperviseReport.docId}'/>";
	if("<c:out value='${noFlow}'/>"=="1"){
		jsonObj.reportIdNull="1";
		
	}*/
	return jsonObj;
}
function freshView(index){
	rootTable.datagrid('collapseRow', index).datagrid("expandRow",index);
}
function showDetails(index,docId){
	if(isNotBlank(docId) && isNotBlank(index)){
		$("#editBranchDiv").dialog('refresh', '<c:url value="/supervise/superviseDeptShow" />?docId='+docId+"&formId=&editFlag=0&index="+index).dialog("open");	
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}
function closeDetails(index){
	$("#editBranchDiv").dialog("close");
	if(index){
		freshView(index);
	}
}


function isNotBlank(value){
	return value != null && value !="null" && value != "" && value != undefined;
}

/*//打开附件（如果为office文件）或者下载附件
function checkDocAttach(attachId,suffixName,attachName,docId){
	var attachSuffix = suffixName.substring(suffixName.lastIndexOf(".") + 1, suffixName.length).toLowerCase();
	if(attachSuffix == "doc" || attachSuffix == "docx" || attachSuffix == "xls" 
			|| attachSuffix == "xlsx" || attachSuffix == 'ppt' 
				|| attachSuffix == 'pptx' || attachSuffix == "pdf"  ) {
		
		var vHeight = window.screen.height -73 ;
		fileReadOnly="<c:out value='${noFlow}' />"!="1" && actionPermissionJson.ModifyAttach!="true";
		var wordUrl =_synergyContext+ "/basic/office/gotoAttachOfficePage?attachId=" + attachId + "&suffixName="+suffixName+"&docId="+docId+"&newFlag=0&fileReadOnly="+fileReadOnly+"&controlId=reportFile&notkHeigth="+vHeight;
		var winFeatures = "height="+vHeight+"px,width="+(window.screen.width-20)+"px,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no";
		window.open(wordUrl,'_blank',winFeatures);
	}else{
		window.location.href =_synergyContext+"/basic/synAttach/downLoadFile?attachId=" + attachId + "&attachName="+attachName+"&suffixName="+suffixName+"&newFlag="+newFlag;
	}
} 

//下载附件
function downloadDocAttach(attachId,suffixName,attachName){
	window.location.href =_synergyContext + "/basic/synAttach/downLoadFile?attachId=" + attachId + "&attachName="+attachName+"&suffixName="+suffixName+"&newFlag=0";
}

function delFileFt(attachId){
	if(isNotBlank(attachId)){
		$.ajax({           
	        type: "POST",                 
	        url: "<c:url value='/superviseReport/delFile'/>",  
	        data:"attachId="+attachId+"&issueId="+$("#docId").val(),
	        dataType: 'json',      
			async:false,            
	        timeout: 5000,                  
	        error: function() {
	        	$.messager.alert("提示",'操作失败');
	        },                  
	        success: function(json) {
	        	if(json.state=="200"){
	        		$("#fileList").empty().hide();
	        	}else{
	        		 $.messager.alert('提示','文件删除失败');
	        	}
	        }});
	}else{
		 $.messager.alert('提示','文件删除失败');
	}
	
}

//修改总附件大小，编辑附件的时候使用
function reportFileChangeTotalSize(value){
	
}
//获取附件总大小，编辑附件的时候使用
function reportFileGetTotalSize(){
	return 0;
}
//获取附件限制大小，编辑附件的时候使用
function reportFileGetFileLimitSize(){
	return 524288000;
}
//获取附件限制大小文字，编辑附件的时候使用
function reportFileGetFileLimitStr(){
	return "";
}
//获取总附件限制大小，编辑附件的时候使用
function reportFileGetAllFileLimitSize(){
	return 524288000;
}
//获取总附件限制大小文字，编辑附件的时候使用
function reportFileGetAllFileLimitStr(){
	return "";
}*/

function saveReport(){
	if(checkPageItems()){
		$("#reportFlag").val("0");
		$.blockUI({ 
			message: '<img src="<c:url value="/images/busy.gif"/>" />&nbsp;&nbsp;<span>正在执行操作 请稍候...</span>', 
			css:{color: '#E17009',fontSize:'17px',padding:'10px'},
			onBlock:function(){	
				$.ajax({//ajax保存表单基本信息
					   type: "POST",
					   url: "<c:url value='/superviseReport/saveReport' />",
					   data: $("#superviseReportForm").serialize(),
					   dataType: "json",
					   async:false,
					   success: function(msg){
					     if(msg.state=="200"){
					    	 if(fileUploadSaveFileFt(_issueId,"0","0","AS","")){//保存附件
					    		 window.location.href=_synergyContext+"/basic/flowItem/"+$("#formId").val()+"/isNew?issueId="+$("#docId").val();
					    	 }
					     }
					   }
					});	
				$.unblockUI();
			}});
	}
}

function saveToCMS(){
	if(checkPageItems()){
		$("#reportFlag").val("1");
		$.blockUI({ 
			message: '<img src="<c:url value="/images/busy.gif"/>" />&nbsp;&nbsp;<span>正在执行操作 请稍候...</span>', 
			css:{color: '#E17009',fontSize:'17px',padding:'10px'},
			onBlock:function(){	
				 if(fileUploadSaveFileFt(_issueId,"0","0","AS","")){//保存附件
						$.ajax({//ajax保存表单基本信息
							   type: "POST",
							   url: "<c:url value='/superviseReport/saveReport' />",
							   data: $("#superviseReportForm").serialize(),
							   dataType: "json",
							   async:false,
							   success: function(msg){
							     if(msg.state=="200"){
							    	
							    		 window.location.href="<c:url value='/superviseReport/add/noFlow' />?dt="+new Date();
							 
							     }
							   }
							});
				 }
				$.unblockUI();
			}});
	}
}

/**
 * 框架页面调用的保存方法
 */
function _saveOAdata(){
	if(!checkPageItems()){//页面验证不通过
		return 1;
	}
	var status = submitOAdata();
	if(status != 100)
	{
		return 2;
	}
	
	return 0;//0:保存成功，1：验证未通过，2：数据保存错误
}

/**
 * 验证
 */
function checkPageItems(){
	if($("#superviseReportForm").form('validate')){
		if(fileUploadGetAllFileNum()==0){
			$.messager.alert('提示','请上传分析报告');
			return false;
		}else{
			return true;
		}
	}
	return false;
}

function submitOAdata(){
	var submitState=500;
	if(checkPageItems()){
		$.ajax({//ajax保存表单基本信息
			   type: "POST",
			   url: "<c:url value='/superviseReport/saveReport' />",
			   data: $("#superviseReportForm").serialize(),
			   dataType: "json",
			   async:false,
			   success: function(msg){
			     if(msg.state=="200"){
			    	 if(fileUploadSaveFileFt(_issueId,"0","0","AS","")){//保存附件
			    		 submitState="100";
			    	 }
			     }
			   }
			});	
	}
	_title=$("#docName").val();
	return submitState;
}